<?php

/*
 *  Copyright (c) 2014 The CCP project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a Beijing Speedtong Information Technology Co.,Ltd license
 *  that can be found in the LICENSE file in the root of the web site.
 *
 *   http://www.yuntongxun.com
 *
 *  An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

/**
 * 发送模板短信
 * @param to 手机号码集合,用英文逗号分开
 * @param datas 内容数据 格式为数组 例如：array('Marry','Alon')，如不需替换请填 null
 * @param $tempId 模板Id
 * 
 */
function sendTemplateSMS($to, $datas, $tempId) {
    //主帐号
    $accountSid = '8a216da866f71d040167073a97bb0649';

    //主帐号Token
    $accountToken = 'c5b7db394353481c9bab4fc4e81eed9a';

    //应用Id
    $appId = '8a216da866f71d040167073a9805064f';

    //请求地址，格式如下，不需要写https://
    $serverIP = 'app.cloopen.com';

    //请求端口 
    $serverPort = '8883';

    //REST版本号
    $softVersion = '2013-12-26';

    // 初始化REST SDK
    import('ytx.rest', EXTEND_PATH, '.class.php');

    $rest = new \REST($serverIP, $serverPort, $softVersion);
    $rest->setAccount($accountSid, $accountToken);
    $rest->setAppId($appId);

    // 发送模板短信
    echo "Sending TemplateSMS to $to <br/>";
    $result = $rest->sendTemplateSMS($to, $datas, $tempId);
    return $result;
    if ($result == NULL) {
        echo "result error!";
    }
    if ($result->statusCode != 0) {
        echo "error code :" . $result->statusCode . "<br>";
        echo "error msg :" . $result->statusMsg . "<br>";
        //TODO 添加错误处理逻辑
    } else {
        echo "Sendind TemplateSMS success!<br/>";
        // 获取返回信息
        $smsmessage = $result->TemplateSMS;
        echo "dateCreated:" . $smsmessage->dateCreated . "<br/>";
        echo "smsMessageSid:" . $smsmessage->smsMessageSid . "<br/>";
        //TODO 添加成功处理逻辑
    }
}

//Demo调用,参数填入正确后，放开注释可以调用 
//sendTemplateSMS("手机号码","内容数据","模板Id");

/**
 *  数据返回格式化
 * @param type $data
 * @param type $code
 * @param type $message
 * @return type
 */
function retData($data, $code, $message) {
    return ['data' => $data, 'code' => $code, 'message' => $message];
}

/**
 * 获取客户端IP地址
 */
function get_real_ip() {
    $ip = false;
    if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
        $ip = $_SERVER['HTTP_CLIENT_IP'];
    }
    if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $ips = explode(', ', $_SERVER['HTTP_X_FORWARDED_FOR']);
        if ($ip) {
            array_unshift($ips, $ip);
            $ip = FALSE;
        }
        for ($i = 0; $i < count($ips); $i++) {
            if (!eregi('^(10│172.16│192.168).', $ips[$i])) {
                $ip = $ips[$i];
                break;
            }
        }
    }
    return ($ip ? $ip : $_SERVER['REMOTE_ADDR']);
}

//参数1：访问的URL，参数2：post数据(不填则为GET)，参数3：提交的$cookies,参数4：是否返回$cookies
function curl_request($url, $post = '', $cookie = '', $returnCookie = 0) {
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)');
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($curl, CURLOPT_AUTOREFERER, 1);
    curl_setopt($curl, CURLOPT_REFERER, "http://www.baidu.com");
    if ($post) {
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($post));
    }
    if ($cookie) {
        curl_setopt($curl, CURLOPT_COOKIE, $cookie);
    }
    curl_setopt($curl, CURLOPT_HEADER, $returnCookie);
    curl_setopt($curl, CURLOPT_TIMEOUT, 10);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    $data = curl_exec($curl);
    if (curl_errno($curl)) {
        return curl_error($curl);
    }
    curl_close($curl);
    if ($returnCookie) {
        list($header, $body) = explode("\r\n\r\n", $data, 2);
        preg_match_all("/Set\-Cookie:([^;]*);/", $header, $matches);
        $info['cookie'] = substr($matches[1][0], 1);
        $info['content'] = $body;
        return $info;
    } else {
        return $data;
    }
}

/**
 * 获取登录地址
 */
function getAddress() {
    $ip = get_real_ip();
    $url = 'http://ip.taobao.com/service/getIpInfo.php?ip=' . $ip;
    $data = json_decode(curl_request($url), TRUE);
    if ($data['code'] == 0) {
        return $data['data']['city'];
    } else {
        return '火星';
    }
}

/**
 * 
 * @param type $dir 存放目录
 * @param type $type 0图片上传，1视频上传
 * @return type
 * 
 * 上传图片
 * 获取阿里云OSS
 */
function MediaUpload($dir,$type=0) {
    
    $ext = ($type==0) ?'jpg':'mp4';
    $config = [
        'maxSize' => 1048576, // 设置附件上传大小
        'exts' => ['jpg', 'gif', 'png', 'jpeg', 'mov', 'mp4'], // 设置附件上传类型
        'rootPath' => './Uploads/' . $dir . '/', // 设置附件上传根目录
        'savePath' => '', // 设置附件上传（子）目录
        'autoSub' => false,
        'subName' => '',
        'saveName' => uniqid() . rand('1000', '9999') .'.'. $ext,
    ];
    $rootPath = $config['rootPath'];
    if (!is_dir($rootPath)) {
        mkdir($rootPath);
    }

    $check = $rootPath . $config['saveName'];
    if (file_exists($check)) {
        unlink($check);
    } else {
        $png = file_get_contents('php://input') ? file_get_contents('php://input') : gzuncompress($GLOBALS ['HTTP_RAW_POST_DATA']); //得到post过来的二进制原始数据  

        if (!empty($png)) {
            $file = @fopen($check, "w");
            fwrite($file, $png); //写入   
            fclose($file); //关闭   
            // orignal image location  
            $write_image = $check;
        } else {
            return retData([], '1001', '上传文件流有问题');
           
        }
    }
    
    $access_key_id = think\Cache::get('ACCESS_KEY_ID');
    $access_key_secret = think\Cache::get('ACCESS_KEY_SECRET');
    $img_url = think\Cache::get('IMG_URL');
    $img_url2 = think\Cache::get('IMG_URL2');
   
    $success = new \Vendor\OSS\OssClient($access_key_id, $access_key_secret, $img_url2);
    $picRemoteName = 'pc_gift_' . time() . rand(100000, 999999) . '.' . $ext;
    $bucket = think\Cache::get('BUCKET');
    $object = 'gift/' . $picRemoteName;
    $filePath = $write_image;
    try {
        $success->uploadFile($bucket, $object, $filePath);
        unlink($rootPath . $picName);
        $img = $img_url . '/' . $object;
        return retData(['imgurl'=>$img], '1000', '上传成功！');      
    } catch (OssException $e) {
        $response = array('ret' => '1002', 'code' => '远程上传错误！');
       return retData([], '1001', '远程上传错误！'); 
    }
    
    
    /**
     * 解析明细
     * @param type $str
     * 打赏
     */
    function getTag($str){
        $prg = '/送给|收到|-?[1-9]\d*/';
        preg_match_all($prg,$str,$data);
        if(!empty($data[0])){
            
        }
        
        // 类型，用户名，礼物名
        //0:固定话术，1获得礼物，2送出礼物，3回复真心话，4提问真心话
        
        
    }
}
